package FenxiaoService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/FenxiaoReq"
	"gdshop-back-end-go/client-api/app/response/GoodsResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-other/GoodsService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"math"
)

func GoodsList(ctx context.Context, parames *FenxiaoReq.GoodsList) *response.JsonResponse {
	dbPrefix := g.Cfg().GetString("database.prefix")
	where := g.Map{
		"g.delete_at < ?": 1,
		"g.id IN (SELECT goods_id FROM " + dbPrefix + "fenxiao_goods WHERE delete_at<1 AND status = ?)": 1,
	}

	if parames.ClassifyId > 0 {
		where["cates"] = "," + gconv.String(parames.ClassifyId) + ","
	}

	jieguo, err := GoodsService.GetPager(ctx, where, parames.Page, parames.PageSize, parames.Sort)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	memberId := int(parames.MemberId)
	// 处理分销信息
	jieguo, err = handleFenxiaoInfo(ctx, memberId, jieguo)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessageData(nil, "成功", jieguo)
}

func GetGoodsIsFollow(ctx context.Context, fenxiaoUserId, goodsId int) bool {
	if fenxiaoUserId < 1 {
		return false
	}
	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_goods_follow").Where(
		"fenxiao_user_id = ? AND goods_id = ?", fenxiaoUserId, goodsId).Fields("1").Count()
	if err != nil {
		return false
	}

	return count > 0
}

// 处理分销信息
func handleFenxiaoInfo(ctx context.Context, memberId int, goodsList *GoodsResp.List) (*GoodsResp.List, error) {
	fenxiaoText := "佣金"
	levelName := ""
	config, err := GetConfig()
	if err != nil {
		levelName = "一级"
	} else {
		if config.SelfPurchaseRebate == 1 {
			levelName = "自购返"
		} else {
			levelName = "一级"
		}
	}

	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, memberId)
	if err != nil {
		return nil, err
	}
	var rate float64
	var fglModel *entity.FenxiaoGoodsLevel
	levelId := GetMemberLevelId(ctx, memberId)

	// 处理佣金信息
	for _, item := range goodsList.List {
		item.FenxiaoInfo = g.Map{
			"fenxiao_text": fenxiaoText,
			"level_name":   levelName,
			"money":        0,
		}
		if memberId > 0 && levelId > 0 {
			// 获取到商品 等级 设置
			fglModel, err = GetGoodsLevel(ctx, int(item.Id), levelId)
			if err != nil {
				// 获取到商品 等级 设置 出错，跳过
				continue
			}
			if fglModel == nil {
				// 获取到商品 等级 设置 出错，跳过
				continue
			}
			if config.SelfPurchaseRebate == 1 {
				// 开启自购佣金
				rate = float64(fglModel.OneRate) / 100000.00
			} else {
				// 正常模式
				rate = float64(fglModel.TwoRate) / 100000.00
			}
			// 这里的金额是分，所以向下取整
			item.FenxiaoInfo["money"] = math.Floor(float64(item.MaxPrice) * rate)
		}

		item.IsFollow = GetGoodsIsFollow(ctx, fuModel.Id, int(item.Id))
	}

	return goodsList, nil
}
